﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MyPeer.cs" company="Exit Games GmbH">
//   Copyright (c) Exit Games GmbH.  All rights reserved.
// </copyright>
// <summary>
//   Defines the MyPeer type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace MyApplication
{
    using System;
    using System.Collections.Generic;
    using DataBaseLayer;
    using ExitGames.Logging;
    using Lite;
    using Lite.Caching;
    using Lite.Common;
    using Lite.Operations;
    using MySQLDB.Business;
    using Newtonsoft.Json;
    using Operations;
    using Photon.SocketServer;
    using PhotonHostRuntimeInterfaces;

    public class MyPeer : LitePeer
    {
        #region Constants and Fields
        private static readonly ILogger log = LogManager.GetCurrentClassLogger();
        #endregion

        #region Constructors and Destructors

        public MyPeer(InitRequest initRequest)
            : base(initRequest)
        {
        }
        #endregion

        #region Methods

        protected override RoomReference GetRoomReference(JoinRequest joinRequest)
        {
            return MyGameCache.Instance.GetRoomReference(joinRequest.GameId, this);
        }

        protected override void OnOperationRequest(OperationRequest operationRequest, SendParameters sendParameters)
        {
            switch (operationRequest.OperationCode)
            {
                case (byte)MyOperationCodes.LoginOperation:  //Login
                    {
                        ToLogin(operationRequest, sendParameters);

                    }
                    break;
                case (byte)MyOperationCodes.ChatOperation: //Chat
                    {
                        ToChat(operationRequest, sendParameters);
                    }
                    break;
                default:
                    {
                        if (log.IsDebugEnabled)
                        {
                            log.DebugFormat("OnOperationRequest. Code={0}", operationRequest.OperationCode);
                        }
                        base.OnOperationRequest(operationRequest, sendParameters);
                        return;
                    }
            }
        }

        private void ToLogin(OperationRequest operationRequest, SendParameters sendParameters)
        {
            //1 Login ok
            string peerJson = (string)operationRequest.Parameters[(byte)MyParameterCodes.UserName];
            device device = JsonConvert.DeserializeObject<device>(peerJson);
            PeerManager.Single.AddPeer(this, device.UUID);

            string welcomeMsg = "";
            string chatHistory = "";
            string logMessage = "";
            if (LoginBussiness.PeerExist(device))
            {
                device.UpdateDate = DateTime.Now;
                welcomeMsg = "欢迎归来!";

                //登录成功，历史聊天记录
                chatHistory = ChatBussiness.GetTop5ChatMessage(device.UUID);
                logMessage = "登录";
            }
            else
            {
                device.UpdateDate = DateTime.Now;
                device.RegisterDate = DateTime.Now;
                device.TokenID = Guid.NewGuid().ToString();
                welcomeMsg = device.DeviceName + ",设备注册成功!";
                logMessage = "注册";
            }

            LogBussiness.InserOrUpdate(new devicelog() { DateTime = DateTime.Now, UUID = device.UUID, log = logMessage });
            LoginBussiness.InserOrUpdate(device);

            OperationResponse opr = new OperationResponse(operationRequest.OperationCode);
            opr.Parameters = new Dictionary<byte, object>();
            opr[(byte)MyParameterCodes.Text] = welcomeMsg;
            opr[(byte)MyParameterCodes.ChatHistory] = chatHistory;

            this.SendOperationResponse(opr, sendParameters);

            BroadcastCCU();
        }

        private void BroadcastCCU()
        {
            Dictionary<byte, object> data = new Dictionary<byte, object>();
            data.Add((byte)MyParameterCodes.Response, "CCU:" + PeerManager.Single.GetPeerCount());
            OperationResponse operRes = new OperationResponse((byte)MyOperationCodes.CCUOperation, data);
            SendParameters SendParameters = new SendParameters();
            foreach (PeerBase peer in PeerManager.Single.GetPeers())
            {
                peer.SendOperationResponse(operRes, SendParameters);
            }
        }

        private void ToChat(OperationRequest operationRequest, SendParameters sendParameters)
        {
            //广播消息
            string userName = PeerManager.Single.GetUserName(this);
            string chat = (string)operationRequest.Parameters[(byte)MyParameterCodes.ChatMessage];
            string msg = string.Format("{0}:{1}\r\n", userName, chat);

            OperationResponse opr = new OperationResponse(operationRequest.OperationCode);
            opr.Parameters = new Dictionary<byte, object>();
            opr[(byte)MyParameterCodes.ChatMessage] = msg;

            ChatBussiness.InserOrUpdate(new devicechat() { chatMsg=chat,
             DateTime = DateTime.Now, UUID = userName});

            ChatManager.Single.AddChat(msg);
            foreach (PeerBase peer in PeerManager.Single.GetPeers())
            {
                peer.SendOperationResponse(opr, sendParameters);
            }
        }

        protected override void HandleLeaveOperation(OperationRequest operationRequest, SendParameters sendParameters)
        {
            base.HandleLeaveOperation(operationRequest, sendParameters);
        }

        protected override void OnDisconnect(DisconnectReason reasonCode, string reasonDetail)
        {
            base.OnDisconnect(reasonCode, reasonDetail);

            this.SaveToDB();
            PeerManager.Single.DeletePeer(this);
            BroadcastCCU();
        }

        #endregion

        /// <summary>
        /// Peer Info Save DB
        /// </summary>
        public void SaveToDB()
        {
            //Info

            //Chat
        }
    }
}